<template>
	<div>
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="900px">
			<el-form ref="dispatchDialogRef" :rules="rules" :model="state.ruleForm" size="default" label-width="90px">
				<el-form-item label="模版名称" prop="dispatchName">
					<el-input v-model="state.ruleForm.dispatchName" placeholder="请输入模版名称" clearable></el-input>
				</el-form-item>

				<el-form-item label="计价方式" prop="calType">
					<el-radio-group v-model="state.ruleForm.calType">
						<el-radio :label="0">按件数</el-radio>
						<el-radio :label="1">按重量</el-radio>
					</el-radio-group>
				</el-form-item>

				<div class="template-wrap">
					<div class="title">
						<div class="area">可配送区域</div>
						<div class="num">
							<span v-if="state.ruleForm.calType == 0"> 首件 </span>
							<span v-else> 首重(kg)</span>
						</div>

						<div class="num">运费(元)</div>
						<div class="num">
							<span v-if="state.ruleForm.calType == 0"> 续件 </span>
							<span v-else> 续重(kg)</span>
						</div>
						<div class="num">续费(元)</div>
						<div class="num">操作</div>
					</div>

					<div>
						<div class="item" v-for="(item, index) in state.ruleForm.areaRates">
							<el-form-item class="area">
								<div>
									<div class="area-font">
										<span v-for="(area, index) in item.areas" :key="index"> {{ area.name }},</span>
									</div>
									<el-button type="primary" @click="onChoiceArea(index)">
										<span>选择地址</span>
									</el-button>
								</div>
							</el-form-item>
							<el-form-item class="num">
								<el-input type="number" v-model="item.firstCount"></el-input>
							</el-form-item>
							<el-form-item class="num">
								<el-input type="number" v-model="item.firstRate" step="0.01"></el-input>
							</el-form-item>
							<el-form-item class="num">
								<el-input type="number" v-model="item.secondCount"></el-input>
							</el-form-item>

							<el-form-item class="num">
								<el-input type="number" v-model="item.secondRate" step="0.01"></el-input>
							</el-form-item>
							<div class="num"><el-button type="danger" link @click="deleteAreaRate(index)">删除</el-button></div>
						</div>

						<el-button type="primary" class="add-btn" plain @click="onAddAreaRates"
							><el-icon> <ele-Plus /> </el-icon>添加</el-button
						>
					</div>
				</div>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(dispatchDialogRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
		<AreaDialog ref="AreaChoiceRef" @choice="callbackChoiceArea"></AreaDialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, defineAsyncComponent } from 'vue';
import { type FormInstance, type FormRules } from 'element-plus';
import { dispatchApi } from '/@/api/shop/dispatch/index';
import _ from 'lodash';
const AreaDialog = defineAsyncComponent(() => import('/@/views/shop/data/area/choice/index.vue'));
const AreaChoiceRef = ref();
const emit = defineEmits(['refresh']);
import messageUtils from '/@/utils/messageUtils';
const dispatchDialogRef = ref();
const state = reactive({
	ruleForm: {
		id: '',
		dispatchName: '',
		content: '',
		calType: 0,
		areaRates: [] as any,
	},
	index: 0,
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});

const rules = reactive<FormRules>({
	activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
	activityTime: [{ required: true, message: '请选择活动时间 ', trigger: 'blur' }],
});
const onCancel = () => {
	closeDialog();
};

const closeDialog = () => {
	console.log('关闭窗口');
	state.dialog.isShowDialog = false;
	state.ruleForm.areaRates = [];
	dispatchDialogRef.value.resetFields();
};

const onChoiceArea = (index: number) => {
	state.index = index;
	let areaIds = state.ruleForm.areaRates[index].areas?.map((e: any) => e.id);
	if (areaIds) {
		console.log('has choice area');
	} else {
		areaIds = [];
		console.log('has no choice area');
	}
	console.log('areaIds: ', areaIds);
	AreaChoiceRef.value.openDialog(areaIds);
};

const deleteAreaRate = (index: number) => {
	state.ruleForm.areaRates.splice(index, 1);
};

const callbackChoiceArea = (choiceAreaDatas: ChoiceAreaData[]) => {
	console.log('choiceAreaDatas: ', choiceAreaDatas);
	state.ruleForm.areaRates[state.index].areas = _.cloneDeep(choiceAreaDatas);

	console.log('state.ruleForm.areaRates[state.index].dispatchAreaReqs: ', state.ruleForm.areaRates[state.index].areas);
};
const onAddAreaRates = () => {
	state.ruleForm.areaRates.push({
		dispatchAreaReqs: [],
		firstRate: 0,
		secondRate: 0,
		firstCount: 0,
		secondCount: 0,
	});
};

const openDialog = async (type: string, id: string) => {
	state.dialog.isShowDialog = true;
	if (type === 'edit') {
		state.dialog.title = '修改模版';
		state.dialog.type = 'edit';
		state.dialog.submitTxt = '更新';
		const { data } = await dispatchApi().view(id);
		console.log('data: ', data);

		state.ruleForm = data;
	} else {
		state.dialog.title = '创建模版';
		state.dialog.type = 'add';
		state.dialog.submitTxt = '新增';
	}
	state.dialog.isShowDialog = true;
};

const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			try {
				if ('edit' === state.dialog.type) {
					await dispatchApi().update({
						id: state.ruleForm.id,
						dispatchName: state.ruleForm.dispatchName,
						calType: state.ruleForm.calType,
						dispatchAreaRates: state.ruleForm.areaRates,
					});
				} else {
					await dispatchApi().create({
						dispatchName: state.ruleForm.dispatchName,
						calType: state.ruleForm.calType,
						dispatchAreaRates: state.ruleForm.areaRates,
					});
				}
				messageUtils().success('操作成功');
				closeDialog();
				emit('refresh');
			} catch (e) {
				messageUtils().error('操作失败,请重试');
			}
		}
	});
};
defineExpose({ openDialog });
</script>

<style scoped lang="scss">
.template-wrap .area {
	width: 320px;
	padding-left: 16px;
}

.template-wrap .title {
	width: inherit;
	background: #f5f5f5;
	height: 40px;
	margin: 0 0 12px;
	font-size: 12px;
	display: flex;
	justify-content: center;
	align-items: center;
}

.template-wrap .area {
	width: 320px;
	padding-left: 16px;
}

.template-wrap .num {
	width: 140px;
	padding-left: 16px;
	font-weight: 700;
}

.template-wrap .item {
	display: flex;
}
.add-btn {
	margin: 16px;
}

:deep(.el-form-item__content) {
	margin-left: 0 !important;
}

.area-font span {
	color: #606266;
	font-size: var(--font-size);
}
</style>
